﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using NJabber.Stream.Elements;

namespace NJabber.Client
{
    public class GenericStanzaHandler : IStanzaHandler
    {
        private ICollection<IStanzaHandler<IqStanza>> iqHandlers = new List<IStanzaHandler<IqStanza>>();
        private ICollection<IStanzaHandler<MessageStanza>> messageHandlers = new List<IStanzaHandler<MessageStanza>>();
        private ICollection<IStanzaHandler<PresenceStanza>> presenceHandlers = new List<IStanzaHandler<PresenceStanza>>();

        public ICollection<IStanzaHandler<IqStanza>> IqHandlers
        {
            get { return iqHandlers; }
        }

        public ICollection<IStanzaHandler<MessageStanza>> MessageHandlers
        {
            get { return messageHandlers; }
        }

        public ICollection<IStanzaHandler<PresenceStanza>> PresenceHandlers
        {
            get { return presenceHandlers; }
        }

        public bool ProcessStanza(XmppClientRuntime runtime, Stanza stanza)
        {
            if (stanza == null) throw new ArgumentNullException("stanza");
            if (stanza is MessageStanza) ProcessMessageStanza(runtime, (MessageStanza)stanza);
            if (stanza is PresenceStanza) ProcessPresenceStanza(runtime, (PresenceStanza)stanza);
            if (stanza is IqStanza) ProccessIqStanza(runtime, (IqStanza)stanza);
            return true;
        }

        private void ProcessMessageStanza(XmppClientRuntime runtime, MessageStanza messageStanza)
        {
            foreach (IStanzaHandler<MessageStanza> handler in messageHandlers)
            {
                handler.ProcessStanza(runtime, messageStanza);
            }
        }

        private void ProcessPresenceStanza(XmppClientRuntime runtime, PresenceStanza presenceStanza)
        {
            foreach (IStanzaHandler<PresenceStanza> handler in presenceHandlers)
            {
                handler.ProcessStanza(runtime, presenceStanza);
            }
        }

        private void ProccessIqStanza(XmppClientRuntime runtime, IqStanza iqStanza)
        {
            foreach (IStanzaHandler<IqStanza> handler in iqHandlers)
            {
                handler.ProcessStanza(runtime, iqStanza);
            }
        }
    }
}
